#include <stdio.h>
#include "plug.h"
#include "plugsdk.h"
#include <unistd.h>
#include "common.h"
#include <string.h>
#include <stdlib.h>

PLUG_CONFIG local_cfg = {0};

int config_line_proc(PLUG_CONFIG *cfg, int argc, char *argv[]){

    int i;

    for(i=1; i<argc; i++){
        if(!strcmp(argv[i], "-m") || !strcmp(argv[i], "--mac")){
            if(i==argc-1){
                fprintf(stderr, "########Error: -m argument given but no mac specified.\n\n");
                return -1;
            }
            else if(strlen(argv[i+1]) != 12){
                fprintf(stderr, "########Error: mac format must be \"aabbccddeeff\".\n\n");
                return -2;
            }else{
                sscanf(argv[i+1], "%02x%02x%02x%02x%02x%02x",
                       (unsigned int*)&cfg->mac[0],
                       (unsigned int*)&cfg->mac[1],
                       (unsigned int*)&cfg->mac[2],
                       (unsigned int*)&cfg->mac[3],
                       (unsigned int*)&cfg->mac[4],
                       (unsigned int*)&cfg->mac[5]);
            }
            i++;
        }
        else if(!strcmp(argv[i], "-f") || !strcmp(argv[i], "--file")){
            if(i==argc-1){
                fprintf(stderr, "########Error: -f argument given but no file specified.\n\n");
                return -3;
            }else{
                if((access(strdup(argv[i+1]),F_OK))!=-1)
                {
                    printf("file %s exist.\n", strdup(argv[i+1]));
                    sprintf(cfg->config_file, "%s", strdup(argv[i+1]));
                }
                else
                {
                    printf("file %s not exist.\n", strdup(argv[i+1]));
                }
            }
            i++;
        }else{
            goto unknown_option;
        }
    }
    return 0;
    unknown_option:
    fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
    return 1;
}

int main( int argc, char * argv[] )
{
	printf("IpDev Version = %d.%d.%d.%d-%s\n\n",
		VERSION_0, VERSION_1, VERSION_2, VERSION_3,RELEASETIME);

    PLUG_CONFIG *p_cfg = &local_cfg;
    if (0 != config_line_proc(p_cfg, argc, argv)){
        fprintf(stderr, "########Error wrong param(s).\n\n");
        return -1;
    }

    // 初始化插件
    if(0!=init_plug_sdk())
    {
        printf("gNetDump init error\n");
        printf("########exit at [%s] %d \n\n", __func__, __LINE__);
        destroy_plug_sdk();
        return -1;
    }


#ifdef DEBUG
    plug_sdk_test();
    return 0;
#else
    while(1)
    	{
        sleep(10);
    	}
#endif

}